<script setup>
import {DeleteIcon, ShareIcon} from "tdesign-icons-vue-next";
import {onMounted, reactive, ref, computed} from "vue";
import {currentUserInfo, terminateUser, updateAvatar, updateUserInfoApi} from "@/api/user.js";
import {useUserStore} from "@/stores/user.js";
import {MessagePlugin} from 'tdesign-vue-next';
import error from "tdesign-icons-vue-next/lib/components/error.js";
import router from "@/router/index.js";

const cover = 'https://tdesign.gtimg.com/site/source/card-demo.png';
const userStore = useUserStore()

// 初始化页面信息 -------------------------------------------------------------------
const userInfo = reactive({
  id: 0,
  username: '',
  nickname: '',
  avatarUrl: '',
  gender: null,
  phone: '',
  email: '',
  university: '',
  college: '',
  major: '',
  role: 0,
});

onMounted(async () => {
  const res = await currentUserInfo(userStore)
  userInfo.id = res.data.data.id
  userInfo.username = res.data.data.username
  userInfo.nickname = res.data.data.nickname
  if (res.data.data.avatarUrl) {
    userInfo.avatarUrl = res.data.data.avatarUrl
  } else {
    userInfo.avatarUrl = "https://tdesign.gtimg.com/site/avatar-boy.jpg"
  }
  userInfo.gender = res.data.data.gender
  userInfo.phone = res.data.data.phone
  userInfo.email = res.data.data.email
  userInfo.university = res.data.data.university
  userInfo.college = res.data.data.college
  userInfo.major = res.data.data.major
  userInfo.role = res.data.data.role
})
// 更新密码的弹窗 ----------------------------------------------------------------------
const passwordData = reactive({
  newPassword : '',
  checkPassword : ''
});


const visibleOverflowPassword = ref(false);
const closePassword = () => {
  visibleOverflowPassword.value = false;
};

const updateWindowPassword = () => {
  visibleOverflowPassword.value = true
}


const onValidate = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    console.log('Validate Success');
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
  }
};

const rePassword = (val) =>
    new Promise((resolve) => {
      const timer = setTimeout(() => {
        resolve(passwordData.newPassword === val);
        clearTimeout(timer);
      });
    });

const passwordValidator = (val) => {
  if (val.length > 0 && val.length <= 2) {
    return { result: false, message: '短', type: 'error' };
  }
  if (val.length > 2 && val.length <= 6) {
    return { result: false, message: '中', type: 'warning' };
  }
  return { result: true, message: '长', type: 'success' };
};

const passwordRule = {
  newPassword: [{ required: true, message: '密码必填', type: 'error' }, { validator: passwordValidator }],
  checkPassword: [
    // 自定义校验规则
    { required: true, message: '密码必填', type: 'error' },
    { validator: rePassword, message: '两次密码不一致' },
  ]

};

const changePassword = async ({e}) => {
  e.preventDefault();
  const res = await updateUserInfoApi(userStore, passwordData.newPassword, '', '', '','', '', '', '')
  if (res.data.code === 40000) await MessagePlugin.error("更新失败: " + res.data.description);
  else {
    await MessagePlugin.success("更新成功");
    visibleOverflowPassword.value = false;
  }
  // if (validateResult === true) {
  //   MessagePlugin.success('提交成功');
  // } else {
  //   console.log('Validate Errors: ', firstError, validateResult);
  //   MessagePlugin.warning(firstError);
  // }
};

// 更新头像的弹窗 ----------------------------------------------------------------------
const visibleOverflowAvatar = ref(false);
const closeAvatar = () => {
  visibleOverflowAvatar.value = false;
};

const updateWindowAvatar = () => {
  visibleOverflowAvatar.value = true
}

const file1 = ref([]);
const uploadAllFilesInOneRequest = ref(false);
const autoUpload = ref(false);
const showImageFileName = ref(true);

const uploadRef1 = ref();

const imageViewerProps = ref({closeOnEscKeydown: false});
const sizeLimit = ref({size: 1, unit: 'MB'});

const handleFail = ({file}) => {
  MessagePlugin.error(`文件 ${file.name} 上传失败`);
};

const uploadFiles = async () => {
  console.log(file1)
  const res = await updateAvatar(userStore, file1.value[0].raw)
  if (res.data.data === true) {
    await MessagePlugin.success("修改成功!")
    const res = await currentUserInfo(userStore)
    userInfo.id = res.data.data.id
    userInfo.username = res.data.data.username
    userInfo.nickname = res.data.data.nickname
    userInfo.avatarUrl = res.data.data.avatarUrl
    userInfo.gender = res.data.data.gender
    userInfo.phone = res.data.data.phone
    userInfo.email = res.data.data.email
    userInfo.university = res.data.data.university
    userInfo.college = res.data.data.college
    userInfo.major = res.data.data.major
    userInfo.role = res.data.data.role
    visibleOverflowAvatar.value = false;
  } else {
    await MessagePlugin.error("修改失败")
  }
};

const formatResponse = () => {
  return {name: 'FileName', error: '网络异常，图片上传失败'};
};



// 更新信息的弹窗 -----------------------------------------------------------------------
const visibleOverflow = ref(false);
const close4 = () => {
  visibleOverflow.value = false;
};

const updateWindow = () => {
  visibleOverflow.value = true
  updateUserInfo.nickname = userInfo.nickname
  updateUserInfo.gender = userInfo.gender
  updateUserInfo.phone = userInfo.phone
  updateUserInfo.email = userInfo.email
  updateUserInfo.college = userInfo.college
  updateUserInfo.major = userInfo.major
}

const form = ref(null);
const updateUserInfo = reactive({
  nickname: '',
  gender: '',
  phone: '',
  email: '',
  college: '',
  major: ''
});

const rules = {
  nickname: [
    {required: false, message: '不大于10个字符', type: 'error', trigger: 'blur'},
    {required: false, message: '不大于10个字符', type: 'error', trigger: 'change'},
    {max: 10, message: '输入字数应不大于10个字符', type: 'error', trigger: 'blur'},
  ],
  gender: [{required: false, message: '性别选填', type: 'warning'}],
  phone: [
    {required: false, message: '电话选填', type: 'warning'},
    {min: 11, message: '仅支持中国11位号码', type: 'error', trigger: 'blur'},
    {max: 11, message: '仅支持中国11位号码', type: 'error', trigger: 'blur'},
  ],
  email: [{required: false, message: '格式必须为邮箱', type: 'warning'}],
  college: [
    // 注意：trigger: blur 仅在输入框或选择框失去焦点时触发，需要注意配合 trigger: change 使用
    {required: false, message: '学院选填', type: 'warning', trigger: 'blur'},
    {required: false, message: '学院选填', type: 'warning', trigger: 'change'},
  ],
  major: [{required: false, message: '专业选填', type: 'warning'}],

};

const emailSuffix = ['@qq.com', '@163.com', '@gmail.com'];
const emailOptions = computed(() => {
  const emailPrefix = updateUserInfo.email.split('@')[0];
  if (!emailPrefix) return [];

  return emailSuffix.map((suffix) => emailPrefix + suffix);
});

const onReset = () => {
  MessagePlugin.success('重置成功');
};

const onSubmit = async ({e}) => {
  e.preventDefault();
  const res = await updateUserInfoApi(userStore, '', updateUserInfo.nickname, '', updateUserInfo.gender, updateUserInfo.phone, updateUserInfo.email, updateUserInfo.college, updateUserInfo.major)
  if (res.data.code === 40000) await MessagePlugin.error("更新失败: " + res.data.description);
  else {
    await MessagePlugin.success("更新成功")
    const res = await currentUserInfo(userStore)
    userInfo.id = res.data.data.id
    userInfo.username = res.data.data.username
    userInfo.nickname = res.data.data.nickname
    userInfo.avatarUrl = res.data.data.avatarUrl
    userInfo.gender = res.data.data.gender
    userInfo.phone = res.data.data.phone
    userInfo.email = res.data.data.email
    userInfo.university = res.data.data.university
    userInfo.college = res.data.data.college
    userInfo.major = res.data.data.major
    userInfo.role = res.data.data.role
    visibleOverflow.value = false;
  }
  // if (validateResult === true) {
  //   MessagePlugin.success('提交成功');
  // } else {
  //   console.log('Validate Errors: ', firstError, validateResult);
  //   MessagePlugin.warning(firstError);
  // }
};

// 删除弹窗 -----------------------------------------------------------------------------------
const terminateVisible = ref(false);

const terminateWindow = (row) => {
  terminateVisible.value = true
}
const terminateClose = () => {
  terminateVisible.value = false;
};

const onClickConfirmTerminate = async () => {
  const res = await terminateUser(userStore);
  if (res.data.data === false) await MessagePlugin.error("注销失败: "+ res.data.description);
  else {
    await MessagePlugin.success("注销成功");
    userStore.removeJwt();
    await router.replace('/login')
  }
}

</script>

<template>
  <t-layout style="height: 100%">
    <t-aside style="
      height: 100%;                /* 继承父容器高度 */
      display: flex;               /* 启用flex布局 */
      align-items: center;         /* 垂直居中 */
      justify-content: center;     /* 水平居中 */
      padding-left: 5%;
      padding-right: 5%;
      width: auto;
    ">
      <t-card :cover="cover" theme="poster2" :style="{ width: '400px' }" shadow>
        <template #footer>
          <t-comment :avatar="userInfo.avatarUrl" :author="userInfo.nickname === null ? '未设置昵称' : userInfo.nickname"
                     :content="(userInfo?.university || '未设置大学') + ' | ' + (userInfo?.phone || '未设置号码')" />
        </template>
        <template #actions>
          <!--          <t-dropdown :min-column-width="112" @click="clickHandler">-->
          <t-dropdown :min-column-width="112">
            <t-button variant="text" shape="square">
              <share-icon/>
            </t-button>
          </t-dropdown>
        </template>
      </t-card>
    </t-aside>
    <t-layout style="
      height: 100%;                /* 继承父容器高度 */
      display: flex;               /* 启用flex布局 */
      align-items: center;         /* 垂直居中 */
      justify-content: center;     /* 水平居中 */
      padding-left: 5%;
      padding-right: 5%;
      background-color: white;
      width: auto;">
      <t-descriptions title="个人信息">
        <t-descriptions-item label="用户名">{{ userInfo.username || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="昵称">{{ userInfo.nickname || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="性别">
          {{
            userInfo.gender === 0 ? '男' : userInfo.gender === 1 ? '女' : '未设置'
          }}
        </t-descriptions-item>
        <t-descriptions-item label="电话号码">{{ userInfo.phone || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="邮箱">{{ userInfo.email || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="学校">{{ userInfo.university || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="学院">{{ userInfo.college || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="专业">{{ userInfo.major || '未设置' }}</t-descriptions-item>
      </t-descriptions>
      <div style="display: flex; justify-content: flex-end; width: 100%; padding-top: 2%">
        <t-button shape="circle" theme="danger" @click="terminateWindow" style="margin-right: 3%">
          <template #icon><DeleteIcon /></template>
        </t-button>
        <t-button theme="primary" @click="updateWindowAvatar" style="margin-right: 3%">更新头像</t-button>
        <t-button theme="primary" @click="updateWindowPassword" style="margin-right: 3%">修改密码</t-button>
        <t-button theme="primary" @click="updateWindow">更新信息</t-button>

      </div>
    </t-layout>

  </t-layout>
<!--  个人信息框-->
  <t-dialog placement="center" header="个人信息更新" :footer="false" :visible="visibleOverflow" :on-confirm="close4"
            :on-close="close4"
            width="50%">
    <t-divider/>
    <t-form ref="form" :data="updateUserInfo" :rules="rules" @reset="onReset" @submit="onSubmit">
      <t-form-item label="昵称" help="昵称不得超过10个字符" name="nickname">
        <t-input v-model="updateUserInfo.nickname"></t-input>
      </t-form-item>

      <t-form-item label="性别" name="gender">
        <t-radio-group v-model="updateUserInfo.gender">
          <t-radio :value="0">男</t-radio>
          <t-radio :value="1">女</t-radio>
        </t-radio-group>
      </t-form-item>

      <t-form-item label="电话" name="phone">
        <t-input v-model="updateUserInfo.phone" filterable></t-input>
      </t-form-item>

      <t-form-item label="邮箱" name="email">
        <t-auto-complete v-model="updateUserInfo.email" :options="emailOptions" filterable></t-auto-complete>
      </t-form-item>


      <t-form-item label="学院" name="college">
        <t-input v-model="updateUserInfo.college"></t-input>
      </t-form-item>
      <t-form-item label="专业" name="major">
        <t-input v-model="updateUserInfo.major"></t-input>
      </t-form-item>

      <t-form-item>
        <t-space size="small">
          <t-button theme="primary" type="submit">提交</t-button>
          <t-button theme="default" variant="base" type="reset">重置</t-button>
        </t-space>
      </t-form-item>
    </t-form>
  </t-dialog>
  <!--  更新框-->
  <t-dialog placement="center" header="更新头像" :footer="false" :visible="visibleOverflowAvatar"
            :on-confirm="closeAvatar"
            :on-close="closeAvatar"
            width="30%">
    <t-divider/>
    <div style="display: flex; justify-content: center">
      <div style="padding-right: 30px">
        <t-image
            :src="userInfo.avatarUrl"
            :style="{ width: '120px', height: '120px' }"
        />
      </div>

      <div style="padding-right: 30px">
        <t-upload
            ref="uploadRef1"
            v-model="file1"
            :image-viewer-props="imageViewerProps"
            :size-limit="sizeLimit"
            theme="image"
            tips="图片大小不超过1MB"
            :auto-upload="autoUpload"
            :show-image-file-name="showImageFileName"
            :upload-all-files-in-one-request="uploadAllFilesInOneRequest"
            :format-response="formatResponse"
            :locale="{
          triggerUploadText: {
            image: '请选择图片替换',
          },
        }"
            @fail="handleFail"
        >
        </t-upload>
        <t-button
            v-if="!autoUpload"
            variant="base"
            theme="default"
            size="small"
            style="height: 22px"
            @click="uploadFiles"
        >
          点击上传
        </t-button>
      </div>
    </div>

  </t-dialog>
  <!--  修改密码框-->
  <t-dialog placement="center" header="修改密码" :footer="false" :visible="visibleOverflowPassword"
            :on-confirm="closePassword"
            :on-close="closePassword"
            width="30%">
    <t-divider/>
    <t-form ref="form" :data="passwordData" :rules="passwordRule" @reset="onReset" @submit="changePassword" @validate="onValidate" >

      <t-form-item label="密码" name="newPassword" help="密码建议大于6位">
        <t-input v-model="passwordData.newPassword" type="password"></t-input>
      </t-form-item>

      <t-form-item label="确认密码" name="checkPassword" help="再次输入密码">
        <t-input v-model="passwordData.checkPassword" type="password"></t-input>
      </t-form-item>

      <t-form-item>
        <t-space size="small">
          <t-button theme="primary" type="submit">提交</t-button>
          <t-button theme="default" variant="base" type="reset">重置</t-button>
        </t-space>
      </t-form-item>
    </t-form>
  </t-dialog>
  <!--  删除提示框-->
  <t-dialog
      v-model:visible="terminateVisible"
      theme="danger"
      header="警示"
      :body="'确定要删除账号吗？'"
      :on-close="terminateClose"
      :cancel-btn="null"
      :confirm-btn="{ theme: 'danger', content: '确认删除' }"
      @confirm="onClickConfirmTerminate"
  />
</template>

<style scoped>

</style>